
const Mock = require('mockjs')

const listData = Mock.mock({
  'list|100': [{
    'id|+1': 1,
    wordname: '@word',
    worddesc: '@title(1,5)',
    'status|1': [0, 1]
  }]
})
module.exports = [
  // 查询，渲染
  {
    url: '/mock/word/list',
    type: 'get',
    response: config => {
      // 读取前端提交的查询参数
      if (config.query.id) {
        const res = listData.list.find(item => item.id * 1 === config.query.id * 1)
        if (res) {
          return {
            code: 200,
            message: '',
            data: res
          }
        }
      } else {
        const { page = 1, limit = 10, worddesc = '', wordname = '' } = config.query

        let cloneList = JSON.parse(JSON.stringify(listData.list))
        let total = listData.list.length
        // 删选
        if (worddesc) {
          cloneList = cloneList.filter(item => item.worddesc.includes(worddesc))
          total = cloneList.length
        }
        // 删选
        if (wordname) {
          cloneList = cloneList.filter(item => item.wordname.includes(wordname))
          total = cloneList.length
        }
        const list = cloneList.splice((page - 1) * limit, limit)
        return {
          status: 200,
          message: 'ok',
          data: {
            list,
            total
          }
        }
      }
    }
  },
  // 添加
  {
    url: '/mock/word/add',
    type: 'post',
    response: (config) => {
      const { body } = config
      if (!body.wordname) {
        return { code: 200, message: '请提交名字', data: '' }
      }
      // 设置默认值
      body.status = body.status === undefined ? 1 : body.status // 设置默认值
      body.id = listData.list[listData.list.length - 1].id + 1
      // 添加到数组中
      listData.list.push(body)
      // 返回
      return { code: 200, message: '添加成功', data: '' }
    }
  },

  // 修改
  {
    url: '/mock/word/update',
    type: 'put',
    response: (config) => {
      const { body } = config
      if (!body.id) {
        return { code: 201, message: '请提交id', data: '' }
      }
      // 找到对应元素
      const index = listData.list.findIndex(
        item => item.id * 1 === body.id * 1
      )
      // 如果没有找到就修改数据
      if (index === -1) {
        return { code: 201, message: '没有该数据', data: '' }
      }
      listData.list[index] = body
      // 返回
      return { code: 200, message: '修改成功', data: '' }
    }
  },
  // 删除
  {
    url: '/mock/word/del',
    type: 'get',
    response: config => {
      const id = config.query.id
      console.log('id:', id)
      if (!id) return { code: 201, message: '请提交id', data: '' }
      // 找到对应元素
      const index = listData.list.findIndex(item => item.id * 1 === id * 1)
      console.log('index', index)
      if (index === -1) {
        // 删除数据
        listData.list.splice(index, 1)
        // 返回
        return { code: 200, message: '修改成功', data: '' }
      }
    }
  }
]
